<template>
  <div class="star-phone" :style="{'color': color, 'font-size': size + 'px'}" :readonly="readonly">
    <span v-for="(star, index) in stars.slice(starNum - rate, starNum * 2 - rate)" :key="index" @click="setStar(index)" :style="{'color': rate > index ? colorSelect : ''}">
      {{star}}
    </span>
  </div>
</template>

<script>
/**
 * @param starNum 星星的个数
 * @param defaultRating 默认选中数
 * @param color-select 星星的选中颜色
 * @param color 星星的选中颜色
 * @param size 星星的大小
 * @param readonly 是否只读
 */
export default {
  name: 'Rate',
  data () {
    return {
      stars: '★★★★★☆☆☆☆☆',
      rate: 0
    }
  },
  props: {
    // 星星的个数
    starNum: {
      type: Number,
      default: 5
    },
    // 默认点亮的个数
    defaultRating: {
      type: Number,
      default: 0
    },
    // 颜色
    color: {
      type: String,
      default: ''
    },
    // 颜色
    colorSelect: {
      type: String,
      default: 'black'
    },
    // 默认大小
    size: {
      type: Number,
      default: 20
    },
    // 是否只读
    readonly: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    setStar (index) {
      if (this.rate === index + 1) {
        this.rate = 0
      } else {
        this.rate = index + 1
      }
      if (!this.readonly) {
        this.$emit('rate-change', this.rate)
      }

    }
  },
  mounted: function () {
    this.stars = '★'.repeat(this.starNum) + '☆'.repeat(this.starNum);
    this.rate = this.defaultRating === 0 ? 0 : this.defaultRating;
  }
}
</script>

<style scoped>
  .star-phone {
    display: inline-block;
    cursor: pointer;
    outline: none;
    -webkit-tap-highlight-color:transparent
  }

  .star-phone span {
    outline: none;
    -webkit-tap-highlight-color:transparent
  }
</style>
